package spikes

import (
	"context"
	"enjoy-shop/formdata"
	"fmt"
	"gitee.com/enjoy_5/order-rpc/client"
	orderpb "gitee.com/enjoy_5/order-rpc/proto/order"
	"gitee.com/enjoy_5/spikes-rpc/client/spikes"
	pb "gitee.com/enjoy_5/spikes-rpc/proto/spikes"
	"github.com/google/uuid"
	"strconv"
)

// 创建订单
func CreateOrder(data formdata.OrderInfo) (*orderpb.OrderInfo, error) {
	var skuId int64

	var pr []*orderpb.OrderGoodsInfo

	for _, val := range data.Pr {
		pr = append(pr, &orderpb.OrderGoodsInfo{
			GoodsId:  val.GoodsId,
			SkuId:    val.SkuId,
			Price:    strconv.FormatInt(val.Price, 10),
			Quantity: val.Quantity,
		})
		skuId = val.SkuId
	}

	//skuId 查询秒杀商品详情
	detail, err := spikes.GetSpikesGoodsDetail(&pb.GetSpikesGoodsDetailRequest{
		SkuID:            skuId,
		SpikesActivityID: data.UpdateStock.SpikesActivityID,
	})

	if err != nil {
		return nil, fmt.Errorf("spikes服务器错误:::%v", err)
	}
	//判断商品库存
	if detail.GetIn().SpikesStock < data.UpdateStock.Num {
		return nil, fmt.Errorf("商品库存不足:::%v", err)
	}

	//计算秒杀价格
	price, err := strconv.ParseFloat(detail.GetIn().SpikesPrice, 2)
	sum := price * float64(data.UpdateStock.Num)

	//生成订单号
	no := uuid.NewString()

	//传参
	oo := &orderpb.OrderInfo{
		OrderNo:        no,
		PayType:        data.PayType,
		AddressId:      data.AddressId,
		UserId:         data.UserId,
		CouponId:       data.CouponId,
		Amount:         strconv.FormatFloat(sum, 'f', 2, 64),
		OrderGoodsInfo: pr,
	}

	fmt.Println("接收到的：：；", oo)
	//调用订单创建接口
	return client.CreateOrder(context.Background(), &orderpb.CreateOrderRequest{In: oo})
}
